<?php

namespace App\Http\Controllers\Admin\Api;

use App\Facades\UserService;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Cartalyst\Sentinel\Checkpoints\ThrottlingException;
use Illuminate\Http\Request;
use Sentinel;

class UserController extends Controller
{
    public function login(Request $request)
    {
        $rules = [
            'username' => 'required',
            'password' => 'required|min:6',
        ];
        $this->validate($request, $rules);

        UserService::login($request->only(['username', 'password']));
        return formatJsonResponse();
    }

    public function updatePassword(Request $request)
    {
        $rules = [
            'password' => 'required|min:6',
            'new_password' => 'required|min:6|confirmed'
        ];
        $this->validate($request, $rules);

        UserService::updatePassword($request->password, $request->new_password);
        return formatJsonResponse();
    }

    public function add(Request $request)
    {
        $rules = [
            'username' => 'required|unique:users,username|max:12',
            'password' => 'required|min:6',
            'phone' => 'telephone',
        ];
        $this->validate($request, $rules);
        
        UserService::addAdmin(
            array_merge($request->only(['username', 'password']), ['is_admin' => 1]),
            $request->only(['name', 'phone']),
            2);
        return formatJsonResponse();
    }

    public function update(Request $request)
    {
        $rules = [
            'user_id' => 'required|exists:users,id',
            'phone' => 'telephone',
        ];
        $this->validate($request, $rules);

        UserService::updateAdminInfo(
            $request->user_id,
            $request->only(['name', 'phone']),
            2);
        return formatJsonResponse();
    }

    public function delete(Request $request)
    {
        $rules = [
            'username' => 'required|exists:users,username',
        ];
        $this->validate($request, $rules);

        UserService::deleteAdmin($request->username);
        return formatJsonResponse();
    }

    public function logout(Request $request)
    {
    	UserService::logout();
    	return formatJsonResponse();
    }

    public function customersFindByName(Request $request)
    {
        $rules = [
            'name' => 'required|exists:user_infos,name',
        ];
        $this->validate($request, $rules);
        
        $customer = UserService::getUserInfoByQuery('name', $request->name);
        return formatJsonResponse(['customer' => $customer]);
    }



}
